home *** CD-ROM | disk | FTP | other *** search
/ Programming a Multiplayer FPS in DirectX / Programming a Multiplayer FPS in DirectX (Companion CD).iso / Source / Chapter 6 / Engine / Engine.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2005-03-29  |  13.3 KB  |  414 lines

  1. //-----------------------------------------------------------------------------
  2. // Engine.h implementation.
  3. // Refer to the Engine.h interface for more details.
  4. //
  5. // Programming a Multiplayer First Person Shooter in DirectX
  6. // Copyright (c) 2004 Vaughan Young
  7. //-----------------------------------------------------------------------------
  8. #include "Engine.h"
  9.  
  10. //-----------------------------------------------------------------------------
  11. // Globals
  12. //-----------------------------------------------------------------------------
  13. Engine *g_engine = NULL;
  14.  
  15. //-----------------------------------------------------------------------------
  16. // Handles Windows messages.
  17. //-----------------------------------------------------------------------------
  18. LRESULT CALLBACK WindowProc( HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam )
  19. {
  20.     switch( msg )
  21.     {
  22.         case WM_ACTIVATEAPP:
  23.             g_engine->SetDeactiveFlag( !wparam );
  24.             return 0;
  25.  
  26.         case WM_DESTROY:
  27.             PostQuitMessage( 0 );
  28.             return 0;
  29.  
  30.         default:
  31.             return DefWindowProc( wnd, msg, wparam, lparam );
  32.     }
  33. }
  34.  
  35. //-----------------------------------------------------------------------------
  36. // The engine class constructor.
  37. //-----------------------------------------------------------------------------
  38. Engine::Engine( EngineSetup *setup )
  39. {
  40.     // Indicate that the engine is not yet loaded.
  41.     m_loaded = false;
  42.  
  43.     // If no setup structure was passed in, then create a default one.
  44.     // Otehrwise, make a copy of the passed in structure.
  45.     m_setup = new EngineSetup;
  46.     if( setup != NULL )
  47.         memcpy( m_setup, setup, sizeof( EngineSetup ) );
  48.  
  49.     // Store a pointer to the engine in a global variable for easy access.
  50.     g_engine = this;
  51.  
  52.     // Prepare and register the window class.
  53.     WNDCLASSEX wcex;
  54.     wcex.cbSize        = sizeof( WNDCLASSEX );
  55.     wcex.style         = CS_CLASSDC;
  56.     wcex.lpfnWndProc   = WindowProc;
  57.     wcex.cbClsExtra    = 0;
  58.     wcex.cbWndExtra    = 0;
  59.     wcex.hInstance     = m_setup->instance;
  60.     wcex.hIcon         = LoadIcon( NULL, IDI_APPLICATION );
  61.     wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );
  62.     wcex.hbrBackground = NULL;
  63.     wcex.lpszMenuName  = NULL;
  64.     wcex.lpszClassName = "WindowClass";
  65.     wcex.hIconSm       = LoadIcon( NULL, IDI_APPLICATION );
  66.     RegisterClassEx( &wcex );
  67.  
  68.     // Initialise the COM using multithreaded concurrency.
  69.     CoInitializeEx( NULL, COINIT_MULTITHREADED );
  70.  
  71.     // Create the Direct3D interface.
  72.     IDirect3D9 *d3d = Direct3DCreate9( D3D_SDK_VERSION );
  73.  
  74.     // Enumerate Direct3D device configurations on the default adapter.
  75.     g_deviceEnumeration = new DeviceEnumeration;
  76.     if( g_deviceEnumeration->Enumerate( d3d ) != IDOK )
  77.     {
  78.         SAFE_RELEASE( d3d );
  79.         return;
  80.     }
  81.  
  82.     // Create the window and retrieve a handle to it.
  83.     m_window = CreateWindow( "WindowClass", m_setup->name, g_deviceEnumeration->IsWindowed() ? WS_OVERLAPPED : WS_POPUP, 0, 0, 800, 600, NULL, NULL, m_setup->instance, NULL );
  84.  
  85.     // Prepare the device presentation parameters.
  86.     D3DPRESENT_PARAMETERS d3dpp;
  87.     ZeroMemory( &d3dpp, sizeof( D3DPRESENT_PARAMETERS ) );
  88.     d3dpp.BackBufferWidth = g_deviceEnumeration->GetSelectedDisplayMode()->Width;
  89.     d3dpp.BackBufferHeight = g_deviceEnumeration->GetSelectedDisplayMode()->Height;
  90.     d3dpp.BackBufferFormat = g_deviceEnumeration->GetSelectedDisplayMode()->Format;
  91.     d3dpp.BackBufferCount = m_setup->totalBackBuffers;
  92.     d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  93.     d3dpp.hDeviceWindow = m_window;
  94.     d3dpp.Windowed = g_deviceEnumeration->IsWindowed();
  95.     d3dpp.EnableAutoDepthStencil = true;
  96.     d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  97.     d3dpp.FullScreen_RefreshRateInHz = g_deviceEnumeration->GetSelectedDisplayMode()->RefreshRate;
  98.     if( g_deviceEnumeration->IsVSynced() == true )
  99.         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
  100.     else
  101.         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  102.  
  103.     // Destroy the device enumeration object.
  104.     SAFE_DELETE( g_deviceEnumeration );
  105.  
  106.     // Create the Direct3D device.
  107.     if( FAILED( d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_window, D3DCREATE_MIXED_VERTEXPROCESSING, &d3dpp, &m_device ) ) )
  108.         return;
  109.  
  110.     // Release the Direct3D interface as it is no longer needed.
  111.     SAFE_RELEASE( d3d );
  112.  
  113.     // Switch lighting off by default.
  114.     m_device->SetRenderState( D3DRS_LIGHTING, false );
  115.  
  116.     // Set the texture filters to use anisotropic texture filtering.
  117.     m_device->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC );
  118.     m_device->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC );
  119.     m_device->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR );
  120.  
  121.     // Set the projection matrix.
  122.     D3DXMATRIX projMatrix;
  123.     D3DXMatrixPerspectiveFovLH( &projMatrix, D3DX_PI / 4, (float)d3dpp.BackBufferWidth / (float)d3dpp.BackBufferHeight, 0.1f / m_setup->scale, 1000.0f / m_setup->scale );
  124.     m_device->SetTransform( D3DTS_PROJECTION, &projMatrix );
  125.  
  126.     // Store the display mode details.
  127.     m_displayMode.Width = d3dpp.BackBufferWidth;
  128.     m_displayMode.Height = d3dpp.BackBufferHeight;
  129.     m_displayMode.RefreshRate = d3dpp.FullScreen_RefreshRateInHz;
  130.     m_displayMode.Format = d3dpp.BackBufferFormat;
  131.  
  132.     // The swap chain always starts on the first back buffer.
  133.     m_currentBackBuffer = 0;
  134.  
  135.     // Create the sprite interface.
  136.     D3DXCreateSprite( m_device, &m_sprite );
  137.  
  138.     // Create the linked lists of states.
  139.     m_states = new LinkedList< State >;
  140.     m_currentState = NULL;
  141.  
  142.     // Create the resource managers.
  143.     m_scriptManager = new ResourceManager< Script >;
  144.  
  145.     // Create the input object.
  146.     m_input = new Input( m_window );
  147.  
  148.     // Create the sound system.
  149.     m_soundSystem = new SoundSystem( m_setup->scale );
  150.  
  151.     // Seed the random number generator with the current time.
  152.     srand( timeGetTime() );
  153.  
  154.     // Allow the application to perform any state setup now.
  155.     if( m_setup->StateSetup != NULL )
  156.         m_setup->StateSetup();
  157.  
  158.     // The engine is fully loaded and ready to go.
  159.     m_loaded = true;
  160. }
  161.  
  162. //-----------------------------------------------------------------------------
  163. // The engine class destructor.
  164. //-----------------------------------------------------------------------------
  165. Engine::~Engine()
  166. {
  167.     // Ensure the engine is loaded.
  168.     if( m_loaded == true )
  169.     {
  170.         // Destroy the states linked lists.
  171.         if( m_currentState != NULL )
  172.             m_currentState->Close();
  173.         SAFE_DELETE( m_states );
  174.  
  175.         // Destroy everything.
  176.         SAFE_DELETE( m_soundSystem );
  177.         SAFE_DELETE( m_input );
  178.         SAFE_DELETE( m_scriptManager );
  179.  
  180.         // Release the sprite interface.
  181.         SAFE_RELEASE( m_sprite );
  182.  
  183.         // Release the device.
  184.         SAFE_RELEASE( m_device );
  185.     }
  186.  
  187.     // Uninitialise the COM.
  188.     CoUninitialize();
  189.  
  190.     // Unregister the window class.
  191.     UnregisterClass( "WindowClass", m_setup->instance );
  192.  
  193.     // Destroy the engine setup structure.
  194.     SAFE_DELETE( m_setup );
  195. }
  196.  
  197. //-----------------------------------------------------------------------------
  198. // Enters the engine into the main processing loop.
  199. //-----------------------------------------------------------------------------
  200. void Engine::Run()
  201. {
  202.     // Ensure the engine is loaded.
  203.     if( m_loaded == true )
  204.     {
  205.         // Show the window.
  206.         ShowWindow( m_window, SW_NORMAL );
  207.  
  208.         // Used to retrieve details about the viewer from the application.
  209.         ViewerSetup viewer;
  210.  
  211.         // Enter the message loop.
  212.         MSG msg;
  213.         ZeroMemory( &msg, sizeof( MSG ) );
  214.         while( msg.message != WM_QUIT )
  215.         {
  216.             if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
  217.             {
  218.                 TranslateMessage( &msg );
  219.                 DispatchMessage( &msg );
  220.             }
  221.             else if( !m_deactive )
  222.             {
  223.                 // Calculate the elapsed time.
  224.                 unsigned long currentTime = timeGetTime();
  225.                 static unsigned long lastTime = currentTime;
  226.                 float elapsed = ( currentTime - lastTime ) / 1000.0f;
  227.                 lastTime = currentTime;
  228.  
  229.                 // Update the input object, reading the keyboard and mouse.
  230.                 m_input->Update();
  231.  
  232.                 // Check if the user wants to make a forced exit.
  233.                 if( m_input->GetKeyPress( DIK_F1 ) )
  234.                     PostQuitMessage( 0 );
  235.  
  236.                 // Request the viewer from the current state, if there is one.
  237.                 if( m_currentState != NULL )
  238.                     m_currentState->RequestViewer( &viewer );
  239.  
  240.                 // Update the current state (if there is one), taking state
  241.                 // changes into account.
  242.                 m_stateChanged = false;
  243.                 if( m_currentState != NULL )
  244.                     m_currentState->Update( elapsed );
  245.                 if( m_stateChanged == true )
  246.                     continue;
  247.  
  248.                 // Begin the scene.
  249.                 m_device->Clear( 0, NULL, viewer.viewClearFlags, 0, 1.0f, 0 );
  250.                 if( SUCCEEDED( m_device->BeginScene() ) )
  251.                 {
  252.                     // Render the current state, if there is one.
  253.                     if( m_currentState != NULL )
  254.                         m_currentState->Render();
  255.  
  256.                     // End the scene and present it.
  257.                     m_device->EndScene();
  258.                     m_device->Present( NULL, NULL, NULL, NULL );
  259.  
  260.                     // Keep track of the index of the current back buffer.
  261.                     if( ++m_currentBackBuffer == m_setup->totalBackBuffers + 1 )
  262.                         m_currentBackBuffer = 0;
  263.                 }
  264.             }
  265.         }
  266.     }
  267.  
  268.     // Destroy the engine.
  269.     SAFE_DELETE( g_engine );
  270. }
  271.  
  272. //-----------------------------------------------------------------------------
  273. // Returns the window handle.
  274. //-----------------------------------------------------------------------------
  275. HWND Engine::GetWindow()
  276. {
  277.     return m_window;
  278. }
  279.  
  280. //-----------------------------------------------------------------------------
  281. // Sets the deactive flag.
  282. //-----------------------------------------------------------------------------
  283. void Engine::SetDeactiveFlag( bool deactive )
  284. {
  285.     m_deactive = deactive;
  286. }
  287.  
  288. //-----------------------------------------------------------------------------
  289. // Returns the scale that the engine is currently running in.
  290. //-----------------------------------------------------------------------------
  291. float Engine::GetScale()
  292. {
  293.     return m_setup->scale;
  294. }
  295.  
  296. //-----------------------------------------------------------------------------
  297. // Returns a pointer to the Direct3D device.
  298. //-----------------------------------------------------------------------------
  299. IDirect3DDevice9 *Engine::GetDevice()
  300. {
  301.     return m_device;
  302. }
  303.  
  304. //-----------------------------------------------------------------------------
  305. // Returns a pointer to the display mode of the current Direct3D device.
  306. //-----------------------------------------------------------------------------
  307. D3DDISPLAYMODE *Engine::GetDisplayMode()
  308. {
  309.     return &m_displayMode;
  310. }
  311.  
  312. //-----------------------------------------------------------------------------
  313. // Returns a pointer to the sprite interface.
  314. //-----------------------------------------------------------------------------
  315. ID3DXSprite *Engine::GetSprite()
  316. {
  317.     return m_sprite;
  318. }
  319.  
  320. //-----------------------------------------------------------------------------
  321. // Adds a state to the engine.
  322. //-----------------------------------------------------------------------------
  323. void Engine::AddState( State *state, bool change )
  324. {
  325.     m_states->Add( state );
  326.  
  327.     if( change == false )
  328.         return;
  329.  
  330.     if( m_currentState != NULL )
  331.         m_currentState->Close();
  332.  
  333.     m_currentState = m_states->GetLast();
  334.     m_currentState->Load();
  335. }
  336.  
  337. //-----------------------------------------------------------------------------
  338. // Removes a state from the engine
  339. //-----------------------------------------------------------------------------
  340. void Engine::RemoveState( State *state )
  341. {
  342.     m_states->Remove( &state );
  343. }
  344.  
  345. //-----------------------------------------------------------------------------
  346. // Changes processing to the state with the specified ID.
  347. //-----------------------------------------------------------------------------
  348. void Engine::ChangeState( unsigned long id )
  349. {
  350.     // Iterate through the list of states and find the new state to change to.
  351.     m_states->Iterate( true );
  352.     while( m_states->Iterate() != NULL )
  353.     {
  354.         if( m_states->GetCurrent()->GetID() == id )
  355.         {
  356.             // Close the old state.
  357.             if( m_currentState != NULL )
  358.                 m_currentState->Close();
  359.  
  360.             // Let the sound system perform garbage collection.
  361.             m_soundSystem->GarbageCollection();
  362.  
  363.             // Set the new current state and load it.
  364.             m_currentState = m_states->GetCurrent();
  365.             m_currentState->Load();
  366.  
  367.             // Swap the back buffers until the first one is in the front.
  368.             while( m_currentBackBuffer != 0 )
  369.             {
  370.                 m_device->Present( NULL, NULL, NULL, NULL );
  371.  
  372.                 if( ++m_currentBackBuffer == m_setup->totalBackBuffers + 1 )
  373.                     m_currentBackBuffer = 0;
  374.             }
  375.  
  376.             // Indicate that the state has changed.
  377.             m_stateChanged = true;
  378.  
  379.             break;
  380.         }
  381.     }
  382. }
  383.  
  384. //-----------------------------------------------------------------------------
  385. // Returns a pointer to the current state.
  386. //-----------------------------------------------------------------------------
  387. State *Engine::GetCurrentState()
  388. {
  389.     return m_currentState;
  390. }
  391.  
  392. //-----------------------------------------------------------------------------
  393. // Returns a pointer to the script manager.
  394. //-----------------------------------------------------------------------------
  395. ResourceManager< Script > *Engine::GetScriptManager()
  396. {
  397.     return m_scriptManager;
  398. }
  399.  
  400. //-----------------------------------------------------------------------------
  401. // Returns a pointer to the input object.
  402. //-----------------------------------------------------------------------------
  403. Input *Engine::GetInput()
  404. {
  405.     return m_input;
  406. }
  407.  
  408. //-----------------------------------------------------------------------------
  409. // Returns a pointer to the sound system.
  410. //-----------------------------------------------------------------------------
  411. SoundSystem *Engine::GetSoundSystem()
  412. {
  413.     return m_soundSystem;
  414. }